package com.example.filesharing.handler;

import com.example.filesharing.utils.FileUtils;
import com.yanzhenjie.andserver.RequestHandler;
import com.yanzhenjie.andserver.RequestMethod;
import com.yanzhenjie.andserver.annotation.RequestMapping;

import org.apache.httpcore.HttpException;
import org.apache.httpcore.HttpRequest;
import org.apache.httpcore.HttpResponse;
import org.apache.httpcore.entity.FileEntity;
import org.apache.httpcore.protocol.HttpContext;

import java.io.File;
import java.io.IOException;
import java.net.URLDecoder;

public class FileListHandler implements RequestHandler {
    @RequestMapping(method={RequestMethod.GET})
    @Override
    public void handle(HttpRequest request, HttpResponse response, HttpContext context) throws HttpException, IOException {
        /*String contentFromBody = HttpRequestParser.getContentFromBody(request);//从请求体中获取数据
        System.out.println("请求体："+contentFromBody);
        String substring = contentFromBody.substring(5, contentFromBody.length());
        String decode= URLDecoder.decode(substring, "utf-8"); */

        String uri = request.getRequestLine().getUri();
        String fileName= uri.substring(10, uri.length());
        String decode = URLDecoder.decode(fileName, "utf-8");
        System.out.println("请求的URI是："+uri);
        System.out.println("文件名是："+fileName);
        System.out.println("解码后的文件名："+decode);
        FileEntity fileEntity=new FileEntity(new File(FileUtils.fileDirectory+"/"+decode));
        response.setHeader("Content-Disposition", "attachment;filename="+decode);//不设置这个就没有下载的效果，举例：如果是txt文件，浏览器就会直接展示文字，而不是下载
        response.setEntity(fileEntity);

    }
}
